Strings to Arrays and Back

This applet demonstrates how array data may be stored to and recovered from strings. For example:

String


Discussion

Tapping on [Add to Array] directly adds data to the array data structure. This structure is converted to a string and shown in the text box labeled "String". This field, too, may be edited. When it senses a field "blur" event, it transforms its string into an array. This array can be sorted, transformed back to a string, and displayed.

This method of converting arrays to strings and back will be particularly useful to PERL programmers.

// String to Array
function stringArray(aString)
{
    var i = 0
    var idx = 0
    var s = ""+aString
    
    if (s == "")
    {
//      this.length = 0
        return this
    }
    
    // search for the colon to create each array item
    while ((idx = s.indexOf(':')) != -1)
    {
        this[i] = s.substring(0, idx)
        s = s.substring(idx+1,s.length)
        i++
    }
    
    // create final array item
    this[i]=s
//  this.length = i+1
    
    return this
}
    
// Array to String
function arrayString(anArray, len)
{
    var s = ""
    
    for (var i = 0; i < (len - 1); i++) s += anArray[i]+":"
    if (len > 0) s += anArray[len - 1]
    return s
}
Copyright ©1998 by Charles River Media, All Rights Reserved